import { AppConfig } from "@/config/config";
import { Http } from "@/net";
import { AppService } from "@/service/app-service";
import { clearCookie, getCookie, setCookie } from "@/utils/util";
import { notification } from "ant-design-vue";
import qs from "qs";

export class AuthGuard {

    /**
     * 权限校验
     *
     * @static
     * @memberof AuthGuard
     */
    public static async checkAuth(router: any): Promise<boolean> {
        return new Promise((resolve: any, reject: any) => {
            const url = '/appdata';
            if (AppConfig && AppConfig.SaaSMode) {
                if (getCookie('activeOrgData')) {
                    this.getAppData(url, router).then((result: any) => {
                        result ? resolve(true) : reject(false);
                    });
                } else {
                    this.getOrgsByDcsystem(router).then((result: boolean) => {
                        if (!result) {
                            reject(false);
                        } else {
                            this.getAppData(url, router).then((result: any) => {
                                result ? resolve(true) : reject(false);
                            });
                        }
                    });
                }
            } else {
                this.getAppData(url, router).then((result: any) => {
                    result ? resolve(true) : reject(false);
                });
            }
        });
    }

    /**
     * 通过租户获取组织数据
     *
     * @memberof AuthGuard
     */
    private static getOrgsByDcsystem(router: any): Promise<boolean> {
        return new Promise((resolve: any) => {
            let tempViewParam = this.hanldeViewParam(window.location.href);
            if (!tempViewParam.srfdcsystem) {
                if (!tempViewParam.redirect) {
                    if (getCookie('dcsystem')) {
                        tempViewParam = JSON.parse(getCookie('dcsystem') as string);
                    }
                } else {
                    tempViewParam = this.hanldeViewParam(tempViewParam.redirect);
                }
            }
            if (!tempViewParam.srfdcsystem && AppConfig.mockDcSystemId) {
                Object.assign(tempViewParam, { srfdcsystem: AppConfig.mockDcSystemId });
            }
            if (tempViewParam.srfdcsystem) {
                setCookie('dcsystem', JSON.stringify(tempViewParam), 1, true);
                let requestUrl: string = `/uaa/getbydcsystem/${tempViewParam.srfdcsystem}`;
                const get: Promise<any> = Http.getInstance().get(requestUrl);
                get.then((response: any) => {
                    if (response && response.status === 200) {
                        let { data }: { data: any } = response;
                        if (data && data.length > 0) {
                            setCookie('orgsData', JSON.stringify(data), 1, true);
                            const user: any = JSON.parse(getCookie('ibzuaa-user') as string);
                            //  用户存在组织数据时设置激活组织数据
                            if (user && user.orgid && user.orgname) {
                                const _orgData = data.find((item: any) => { return item.orgid === user.orgid && item.orgname === user.orgname });
                                setCookie('activeOrgData', JSON.stringify(_orgData), 1, true);
                            } else {
                                setCookie('activeOrgData', JSON.stringify(data[0]), 1, true);
                            }
                        }
                        resolve(true);
                    } else {
                        resolve(false);
                    }
                }).catch(() => {
                    this.goLogin(router).then((result: any) => {
                        resolve(result);
                    })
                });
            } else {
                this.goLogin(router).then((result: any) => {
                    resolve(result);
                })
            }
        });
    }

    /**
     * 获取应用数据
     *
     * @param {string} url url 请求路径
     * @param {*} [router] 路由对象
     * @param {*} [params={}] 请求参数
     * @returns {Promise<boolean>} 是否通过
     * @memberof AuthGuard
     */
    private static getAppData(url: string, router: any, _params: any = {}): Promise<boolean> {
        return new Promise((resolve: any) => {
            const get: Promise<any> = Http.getInstance().get(url);
            get.then((response: any) => {
                if (response && response.status === 200) {
                    let { data }: { data: any } = response;
                    if (data && Object.keys(data).length >0) {
                        AppService.getInstance().setAppData(data);
                    }
                }
                resolve(true)
            }).catch(() => {
                this.goLogin(router).then((result: any) => {
                    resolve(result);
                })
            });
        });
    }

    /**
     * 处理路径数据
     *
     * @param {*} [urlStr] 路径
     *
     * @memberof AuthGuard
     */
    private static hanldeViewParam(urlStr: string): any {
        let tempViewParam: any = {};
        const tempViewparam: any = urlStr.slice(urlStr.indexOf('?') + 1);
        const viewparamArray: Array<string> = decodeURIComponent(tempViewparam).split(';');
        if (viewparamArray.length > 0) {
            viewparamArray.forEach((item: any) => {
                Object.assign(tempViewParam, qs.parse(item));
            });
        }
        return tempViewParam;
    }

    /**
     * 跳转登录
     *
     * @static
     * @memberof AuthGuard
     */
    private static async goLogin(router: any) {
        AppService.getInstance().clearAppData();
        if (Object.is(router.currentRoute.name, 'Login')) {
            notification.error({
                message: '登录失败',
                description: '登录失败，请联系管理员'
            });
            return;
        }
        router.push({ name: 'Login' });
        return false;
    }
}